package org.jeecg.config.feign;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String s, Response response) {
        log.warn("进入错误码拦截器-------------------------------------");
        try {
            if (response.body() != null) {
                //会把异常信息转换成字符串，注意断点不要打在这一行，会报IO异常
                //断点可以打在它的下一行
                String body = Util.toString(response.body().asReader(Charset.defaultCharset()));
                log.warn("进入错误码拦截器 {}", body);
                //将字符串转换为自定义的异常信息
//                JSONObject object = JSONUtil.parseObj(body);
//                MingnaFeignException mingnaFeignException = new MingnaFeignException();
//                mingnaFeignException.setCode(object.getInt("status"));
//                mingnaFeignException.setMsg(object.getStr("error"));
//                mingnaFeignException.setData(body);
                return new Exception(body);
            }
        } catch (Exception ex){
            //异常记录日志
            log.warn("Feign异常处理错误：", ex);
        }

        return new Exception(s);
    }
}
